<?php

namespace app\index\model;

use think\Model;
use think\Db;

class User extends Model
{
    // 根据条件,搜索学员信息
    public function userAll($searchList)
    {
        // 学员信息
        if (empty($searchList)) {
            // 若无搜索条件, 则按照可显示班期,查出所有学员
            $searchList = ['c.cover' => 1];
            $users = Db::table('s_user')->alias('u')
                ->field(['u.id', 'u.uname', 'u.usex', 'u.utel', 'u.uclass', 'u.ustatus', 'u.umarks'])
                ->join('s_class c', 'c.class_name = u.uclass')
                ->where($searchList)
                ->order(['u.ustatus' => 'DESC', 'u.uclass' => 'DESC', 'u.id' => 'DESC'])
                ->limit(120)
                ->select();
        } else {
            // 若有查询条件,则按照条件查出学员
            $users = Db::name('user')
                ->field(['id', 'uname', 'usex', 'utel', 'uclass', 'ustatus', 'umarks'])
                ->where($searchList)
                ->order(['ustatus' => 'DESC', 'uclass' => 'DESC', 'id' => 'DESC'])
                ->limit(120)
                ->select();
        }
        // 取出学员们的ID
        $ids = [];
        foreach ($users as $v) {
            $ids[] = $v['id'];
        }
        // 查出以上学员的扣分信息
        $scoreList = Db::table('s_user')
            ->alias('u')
            ->field(['u.id', 's.uid', 's.score'])
            ->where('s.uid', 'in', $ids)
            ->join('s_score s', 's.uid = u.id')
            ->order(['u.ustatus' => 'DESC', 'u.id' => 'DESC'])
            ->select();
        // 算出剩余积分
        foreach ($users as $key => $val) {
            $users[$key]['scoreSum'] = 100;
            foreach ($scoreList as $v) {
                if ($val['id'] == $v['uid']) {
                    $users[$key]['scoreSum'] -= $v['score'];
                }
            }
        }
        return $users;
    }
}
